package com.example.springboot2.controller;

import com.example.springboot2.common.Result;
import com.example.springboot2.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 文件上传控制器
 */
@Slf4j
@RestController
@RequestMapping("/upload")
public class FileController {

    @Value("${file.upload.path}")
    private String uploadPath;

    /**
     * 文件上传
     */
    @PostMapping
    public Result<Map<String, String>> uploadFile(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            throw new BusinessException("文件不能为空");
        }

        try {
            // 获取原始文件名
            String originalFilename = file.getOriginalFilename();
            if (originalFilename == null) {
                throw new BusinessException("文件名不能为空");
            }

            // 获取文件扩展名
            String extension = "";
            int dotIndex = originalFilename.lastIndexOf('.');
            if (dotIndex > 0) {
                extension = originalFilename.substring(dotIndex);
            }

            // 生成新的文件名
            String newFilename = UUID.randomUUID().toString() + extension;

            // 按日期创建目录
            String dateDir = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy/MM/dd"));
            Path uploadDir = Paths.get(uploadPath, dateDir);
            
            // 创建目录
            if (!Files.exists(uploadDir)) {
                Files.createDirectories(uploadDir);
            }

            // 保存文件
            Path filePath = uploadDir.resolve(newFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 构建文件访问URL
            String fileUrl = "/files/" + dateDir + "/" + newFilename;

            Map<String, String> result = new HashMap<>();
            result.put("url", fileUrl);
            result.put("filename", originalFilename);
            result.put("size", String.valueOf(file.getSize()));

            log.info("文件上传成功: {} -> {}", originalFilename, fileUrl);
            return Result.success("文件上传成功", result);

        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new BusinessException("文件上传失败: " + e.getMessage());
        }
    }

    /**
     * 文件下载
     */
    @GetMapping("/files/**")
    public ResponseEntity<Resource> downloadFile(@RequestParam String filename) {
        try {
            Path filePath = Paths.get(uploadPath).resolve(filename).normalize();
            Resource resource = new UrlResource(filePath.toUri());

            if (resource.exists() && resource.isReadable()) {
                // 尝试确定文件的内容类型
                String contentType = Files.probeContentType(filePath);
                if (contentType == null) {
                    contentType = "application/octet-stream";
                }

                return ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType(contentType))
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                        .body(resource);
            } else {
                throw new BusinessException("文件不存在或不可读");
            }
        } catch (MalformedURLException e) {
            log.error("文件下载失败", e);
            throw new BusinessException("文件下载失败: " + e.getMessage());
        } catch (IOException e) {
            log.error("文件下载失败", e);
            throw new BusinessException("文件下载失败: " + e.getMessage());
        }
    }

    /**
     * 批量文件上传
     */
    @PostMapping("/batch")
    public Result<Map<String, Object>> uploadFiles(@RequestParam("files") MultipartFile[] files) {
        if (files.length == 0) {
            throw new BusinessException("文件不能为空");
        }

        Map<String, Object> result = new HashMap<>();
        result.put("success", 0);
        result.put("failed", 0);
        result.put("files", new HashMap<String, String>());

        for (MultipartFile file : files) {
            try {
                Result<Map<String, String>> uploadResult = uploadFile(file);
                if (uploadResult.getCode() == 200) {
                    result.put("success", (Integer) result.get("success") + 1);
                    @SuppressWarnings("unchecked")
                    Map<String, String> filesMap = (Map<String, String>) result.get("files");
                    filesMap.put(file.getOriginalFilename(), uploadResult.getData().get("url"));
                }
            } catch (Exception e) {
                result.put("failed", (Integer) result.get("failed") + 1);
                log.error("批量上传文件失败: {}", file.getOriginalFilename(), e);
            }
        }

        return Result.success("批量上传完成", result);
    }
}
